import "./swiper.css"
import { useState, useEffect } from "react"

function Swiper(props: { list: string[], timeout: number }) {
    const [currentIndex, setCurrentIndex] = useState(-1)
    const getActive: (index: number) => string = (index) => {
        if (index === currentIndex) {
            return "active"
        }
        return ""
    }
    useEffect(() => {
        setCurrentIndex(0)
    }, [])
    useEffect(() => {
        start()
    }, [currentIndex])

    const start = () => {
        setTimeout(() => {
            let index = currentIndex + 1
            if (index === props.list.length) {
                index = 0
            }
            setCurrentIndex(index)
        }, props.timeout)
    }

    return (
        <div className="swiper">
            <div className="swiper-views">
                {props.list.map((url, index) => {
                    return (
                        <div className={["swiper-views-item", getActive(index)].join(' ')} key={url}>
                            <img src={url} />
                        </div>
                    )
                })}
            </div>
            <div className="swiper-pager" style={{ "--timeout": props.timeout + "ms" } as React.CSSProperties}>
                {props.list.map((url, index) => <span key={url} className={getActive(index)}></span>)}
            </div>
        </div >
    )
}

export default Swiper
